package com.android.fastwebview.webview

import android.annotation.SuppressLint
import android.content.Context
import android.content.MutableContextWrapper
import android.os.Looper
import android.os.MessageQueue
import java.util.*


@SuppressLint("StaticFieldLeak")
object WebViewPool {

    private const val CACHED_WEB_VIEW_MAX_NUM = 3

    private lateinit var context: Context

    private val webViewCacheStack = Stack<FastWebView>()

    fun init(context: Context){
        this.context = context
        preload()
    }

    /**
     * WebView预加载
     */
    fun preload() {
        Looper.myQueue().addIdleHandler(object : MessageQueue.IdleHandler {
            override fun queueIdle(): Boolean {
                if (webViewCacheStack.size < CACHED_WEB_VIEW_MAX_NUM) {
                    webViewCacheStack.push(createWebView())
                }
                return false
            }
        })
    }

    /**
     * 取出对象池的WebView并且替换context为当前Activity的context
     */
    fun acquire(context: Context): FastWebView {
        if (webViewCacheStack.isEmpty()) {
            return createWebView()
        }
        val webView = webViewCacheStack.pop()
        val contextWrapper = webView.context as MutableContextWrapper
        contextWrapper.baseContext = context
        return webView
    }

    /**
     * 创建WebView
     */
    private fun createWebView(): FastWebView {
        return FastWebView(MutableContextWrapper(context))
    }



}